<?php

namespace mpend\modules\h5\models;

use yii\data\ActiveDataProvider;
use yii\db\Exception;
use mpend\modules\h5\models\logic\Search;
use common\models\mongo\DynamicMess;
use common\models\mongo\DynamicMessCount;

class DynamicMessageSearch extends Search {

    public function search($params = []) {
        $user = $this->user;
        if (!$user) {
            throw new Exception('用户令牌无效');
        }
        $model = new DynamicMess();
        $query = $model::find()
        ->where([
            'passive_user_id' => $user->id
        ])->orderBy('created_at desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->clearNewMess($user->id);

        return $dataProvider;
    }

    //每次查看新消息时,新消息数目
    private function clearNewMess($user_id) {
        $dynamicMessCount = DynamicMessCount::findOne(['user_id' => $user_id]);
        if ($dynamicMessCount) {
            $dynamicMessCount->mess_cnt = 0;
            $dynamicMessCount->save();
        }
        return true;
    }

}
